import { Component, OnInit, inject } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { PostService } from '../../services/post.service';
import { CategoryService } from '../../services/category.service';
import { FileService } from '../../services/file.service';
import { Post, CreatePostRequest, UpdatePostRequest, QueryParams, Category, BlogFile } from '../../models/blog.model';

@Component({
  selector: 'app-manage-blogpost',
  standalone: false,
  templateUrl: './manage-blogpost.component.html',
  styleUrl: './manage-blogpost.component.less'
})
export class ManageBlogpostComponent implements OnInit {
  // 依赖注入
  private fb = inject(FormBuilder);
  private postService = inject(PostService);
  private categoryService = inject(CategoryService);
  private fileService = inject(FileService);
  private message = inject(NzMessageService);

  // 数据属性
  posts: Post[] = [];
  categories: Category[] = [];
  files: BlogFile[] = [];
  loading = false;
  
  // 分页属性
  pageIndex = 1;
  pageSize = 10;
  total = 0;
  
  // 搜索属性
  searchValue = '';
  selectedCategory = '';
  
  // 模态框属性
  isModalVisible = false;
  modalTitle = '添加文章';
  editingPost: Post | null = null;
  
  // 表单
  postForm: FormGroup;

  constructor() {
    this.postForm = this.fb.group({
      title: ['', [Validators.required, Validators.minLength(1), Validators.maxLength(100)]],
      desc: ['', [Validators.required, Validators.minLength(1), Validators.maxLength(500)]],
      category: ['', [Validators.required]],
      file: ['', [Validators.required]]
    });
  }

  ngOnInit(): void {
    this.loadPosts();
    this.loadCategories();
  }

  /**
   * 加载文章列表
   */
  loadPosts(): void {
    this.loading = true;
    const params: QueryParams = {
      page: this.pageIndex,
      size: this.pageSize,
      q: this.searchValue || undefined,
      category: this.selectedCategory || undefined
    };

    this.postService.getPosts(params).subscribe({
      next: (response) => {
        console.log(response);
        if (response.status && response.data) {
          this.posts = response.data.posts;
          this.total = response.data.total;
        }
        this.loading = false;
      },
      error: (error) => {
        console.error('加载文章失败:', error);
        this.message.error('加载文章失败');
        this.loading = false;
      }
    });
  }

  /**
   * 加载分类列表
   */
  loadCategories(): void {
    this.categoryService.getCategories({ size: 100 }).subscribe({
      next: (response) => {
        if (response.status && response.data) {
          this.categories = response.data.categories;
        }
      },
      error: (error) => {
        console.error('加载分类失败:', error);
        this.message.error('加载分类失败');
      }
    });
  }

  /**
   * 搜索文章
   */
  onSearch(): void {
    this.pageIndex = 1;
    this.loadPosts();
  }

  /**
   * 重置搜索
   */
  onSearchReset(): void {
    this.searchValue = '';
    this.selectedCategory = '';
    this.pageIndex = 1;
    this.loadPosts();
  }

  /**
   * 分页变化
   */
  onPageIndexChange(pageIndex: number): void {
    this.pageIndex = pageIndex;
    this.loadPosts();
  }

  /**
   * 页面大小变化
   */
  onPageSizeChange(pageSize: number): void {
    this.pageSize = pageSize;
    this.pageIndex = 1;
    this.loadPosts();
  }

  /**
   * 显示添加模态框
   */
  showAddModal(): void {
    this.modalTitle = '添加文章';
    this.editingPost = null;
    this.postForm.reset();
    this.isModalVisible = true;
  }

  /**
   * 显示编辑模态框
   */
  showEditModal(post: Post): void {
    this.modalTitle = '编辑文章';
    this.editingPost = post;
    this.postForm.patchValue({
      title: post.title,
      desc: post.desc,
      category: typeof post.category === 'string' ? post.category : post.category._id,
      file: typeof post.file === 'string' ? post.file : post.file._id
    });
    this.isModalVisible = true;
  }

  /**
   * 关闭模态框
   */
  handleModalCancel(): void {
    this.isModalVisible = false;
    this.postForm.reset();
    this.editingPost = null;
  }

  /**
   * 提交表单
   */
  handleModalOk(): void {
    if (this.postForm.valid) {
      const formValue = this.postForm.value;
      
      if (this.editingPost) {
        // 编辑文章
        this.updatePost(this.editingPost._id, formValue);
      } else {
        // 添加文章
        this.createPost(formValue);
      }
    } else {
      // 标记所有字段为已触摸，以显示验证错误
      Object.values(this.postForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  /**
   * 创建文章
   */
  createPost(data: CreatePostRequest): void {
    this.postService.createPost(data).subscribe({
      next: (response) => {
        this.message.success('文章创建成功');
        this.isModalVisible = false;
        this.postForm.reset();
        this.loadPosts();
      },
      error: (error) => {
        console.error('创建文章失败:', error);
        this.message.error('创建文章失败');
      }
    });
  }

  /**
   * 更新文章
   */
  updatePost(id: string, data: UpdatePostRequest): void {
    this.postService.updatePost(id, data).subscribe({
      next: (response) => {
        this.message.success('文章更新成功');
        this.isModalVisible = false;
        this.postForm.reset();
        this.editingPost = null;
        this.loadPosts();
      },
      error: (error) => {
        console.error('更新文章失败:', error);
        this.message.error('更新文章失败');
      }
    });
  }

  /**
   * 删除文章
   */
  deletePost(id: string): void {
    this.postService.deletePost(id).subscribe({
      next: (response) => {
        this.message.success('文章删除成功');
        this.loadPosts();
      },
      error: (error) => {
        console.error('删除文章失败:', error);
        this.message.error('删除文章失败');
      }
    });
  }

  /**
   * 格式化日期
   */
  formatDate(dateString: string): string {
    return new Date(dateString).toLocaleDateString('zh-CN');
  }

  /**
   * 获取分类名称
   */
  getCategoryName(category: Category | string): string {
    if (typeof category === 'string') {
      const cat = this.categories.find(c => c._id === category);
      return cat ? cat.title : '未知分类';
    }
    return category.title;
  }

  /**
   * 获取文件名称
   */
  getFileName(file: BlogFile | string): string {
    if (typeof file === 'string') {
      return '文件ID: ' + file;
    }
    // 从文件key中提取文件名
    return this.extractFileNameFromKey(file.key);
  }

  /**
   * 从文件key中提取文件名
   */
  private extractFileNameFromKey(key: string): string {
    return key.split('/').pop() || key;
  }

  /**
   * 获取作者名称
   */
  getAuthorName(post: Post): string {
    if (typeof post.updatedBy === 'string') {
      return '用户ID: ' + post.updatedBy;
    }
    return post.updatedBy?.name || '未知作者';
  }

  /**
   * 获取表单控件的错误信息
   */
  getFormControlError(controlName: string): string {
    const control = this.postForm.get(controlName);
    if (control && control.errors && control.dirty) {
      if (control.errors['required']) {
        const fieldNames: { [key: string]: string } = {
          title: '文章标题',
          desc: '文章描述',
          category: '分类',
          file: '文件'
        };
        return `${fieldNames[controlName]}不能为空`;
      }
      if (control.errors['minlength']) {
        return `内容长度至少为${control.errors['minlength'].requiredLength}个字符`;
      }
      if (control.errors['maxlength']) {
        return `内容长度不能超过${control.errors['maxlength'].requiredLength}个字符`;
      }
    }
    return '';
  }
}
